package org.penguin.study.bk.service.impl

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import org.penguin.study.bk.dao.MessageJpaDao
import org.penguin.study.bk.dao.MessageMapper
import org.penguin.study.bk.entity.Message
import org.penguin.study.bk.service.MessageService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.util.StringUtils
import java.time.LocalDateTime
import java.util.*
import javax.annotation.Resource

@Service
class MessageServiceImpl : MessageService { // , ServiceImpl<MessageMapper, Message>()

    @Resource
    lateinit var messageMapper: MessageMapper

    @Autowired
    lateinit var messageJpaDao: MessageJpaDao

    override fun now(): Date {
        val now = messageMapper.now()
        return now
    }

    override fun queryByText(text: String): List<Message> {
        return messageMapper.queryByText(text)
    }

    override fun plusPageByQW(page: Page<Message>, queryWrapper: QueryWrapper<Message>?) =
        messageMapper.selectPage(page, queryWrapper)

    override fun plusPageByLambdaQW(page: Page<Message>, queryWrapper: LambdaQueryWrapper<Message>?) =
        messageMapper.selectPage(page, queryWrapper)

    override fun saveOrUpdateByJPA(message: Message): Message {
        if (StringUtils.hasLength(message.id)) {
            val existMessage = messageJpaDao.findById(message.id!!)
            if (existMessage.isPresent) {
                with(existMessage.get()) {
                    text = message.text
                    updatedBy = message.updatedBy
                    updatedTime = LocalDateTime.now()
                    messageJpaDao.saveAndFlush(this)
                    return this
                }
            } else {
                message.id = null
                return messageJpaDao.saveAndFlush(message)
            }
        } else {
            return messageJpaDao.saveAndFlush(message)
        }
    }

    override fun saveOrUpdateByPlus(message: Message): Message {
        if (StringUtils.hasLength(message.id)) {
            messageMapper.updateById(message)
        } else {
            message.id = null
            messageMapper.insert(message)
        }
        return message
    }
}
